import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Radio,
  Select,
  Space,
  Table,
  Tooltip
} from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { safeEmployeeCertificatesUserList } from '@/services/bizApi/anquanrenyuanchizhengxinxibiaojiekou';
import {
  equDefectConfirmMaintenance,
  equDefectConfirmMeasure,
  equDefectConfirmMember,
  equDefectConfirmSupervisor,
  equDefectConfirmSupervisorAgain,
  equDefectGet,
  equDefectReport
} from '@/services/bizApi/shebaoquexianjiekou';
import { ProFormSelect } from '@ant-design/pro-form';
import { Icon } from '@iconify/react/dist/iconify.js';

import { BizObject } from './';
import Device, { DeviceRef } from './device';
import Equipment, { EquipmentRef } from './equipment';
import Paper, { PaperRef } from './paper';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
          rowData?: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const maintenanceInternal = Form.useWatch('maintenanceInternal', form);
  const maintenanceInHouse = Form.useWatch('maintenanceInHouse', form);
  const device = useRef<DeviceRef>(null);
  const equipment = useRef<EquipmentRef>(null);
  const paper = useRef<PaperRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [deviceDataSource, setDeviceDataSource] = useState<BIZAPI.EquInfoEntity[]>([]);
  const [equipmentDataSource, setEquipmentDataSource] = useState<BIZAPI.EquInfoEntity[]>([]);
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const equDefect = useRequest(
    async (id: string) => {
      const res = await equDefectGet({ id });
      form.setFieldsValue({
        ...res?.data,
        ...res?.data?.detail,
        maintenanceMember: res?.data?.maintenanceMember?.split(','),
        dangerPoint: res?.data?.detail?.dangerPoint?.split(','),
        protectiveMeasure: res?.data?.detail?.protectiveMeasure?.split(','),
        maintenancePlan: res?.data?.maintenancePlanBeginTime
          ? [dayjs(res?.data?.maintenancePlanBeginTime), dayjs(res?.data?.maintenancePlanEndTime)]
          : undefined,
        maintenanceType: res?.data?.defectStatus === 31 ? undefined : res?.data?.maintenanceType,
        dangerPointOther: res?.data?.detail?.dangerPointOther
          ? res?.data?.detail?.dangerPointOther
          : '无',
        protectiveMeasureOther: res?.data?.detail?.protectiveMeasureOther
          ? res?.data?.detail?.protectiveMeasureOther
          : '无',
        measuresEnergy: res?.data?.detail?.measuresEnergy
          ? res?.data?.detail?.measuresEnergy
          : '无',
        measuresSafety: res?.data?.detail?.measuresSafety
          ? res?.data?.detail?.measuresSafety
          : '无',
        measuresWarning: res?.data?.detail?.measuresWarning
          ? res?.data?.detail?.measuresWarning
          : '无',
        measuresExtra: res?.data?.detail?.measuresExtra ? res?.data?.detail?.measuresExtra : '无',
        measuresContent: res?.data?.detail?.measuresContent
          ? res?.data?.detail?.measuresContent
          : '无'
      });
      setEquipmentDataSource(res?.data?.inventoryList || []);
      return res?.data;
    },
    {
      manual: true
    }
  );
  const submit = useRequest(
    async ({
      _type,
      dangerPointOther,
      protectiveMeasureOther,
      measuresEnergy,
      measuresSafety,
      measuresWarning,
      measuresExtra,
      measuresContent,
      ...values
    }) => {
      const query = {
        ...values,
        maintenanceMember: values?.maintenanceMember?.join(','),
        processLeaderName: userInfo?.data?.filter(
          (item) => item.id === values?.processLeaderId
        )?.[0]?.fullName,
        maintenanceLeaderName: userInfo?.data?.filter(
          (item) => item.id === values?.maintenanceLeaderId
        )?.[0]?.fullName,
        maintenancePlanBeginTime: values?.maintenancePlan?.[0]
          ? dayjs(values?.maintenancePlan?.[0]).format('YYYY-MM-DD HH:mm')
          : undefined,
        maintenancePlanEndTime: values?.maintenancePlan?.[1]
          ? dayjs(values?.maintenancePlan?.[1]).format('YYYY-MM-DD HH:mm')
          : undefined
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      if (args?.type === 'add') {
        await equDefectReport(query);
      }

      if (
        args?.rowData?.defectStatus === 10 ||
        args?.rowData?.defectStatus === 11 ||
        args?.rowData?.defectStatus === 13 ||
        args?.rowData?.defectStatus === 32 ||
        args?.rowData?.defectStatus === 44
      ) {
        query.inventoryList = equipmentDataSource;
        query.detail = {
          dangerPoint: values?.dangerPoint?.join(','),
          dangerPointOther,
          protectiveMeasure: values?.protectiveMeasure?.join(','),
          protectiveMeasureOther,
          measuresEnergy,
          measuresSafety,
          measuresWarning,
          measuresExtra,
          measuresContent
        };
        await (args?.rowData?.defectStatus === 10
          ? equDefectConfirmSupervisor(query)
          : args?.rowData?.defectStatus === 11
            ? equDefectConfirmMaintenance(query)
            : args?.rowData?.defectStatus === 13
              ? equDefectConfirmMember(query)
              : equDefectConfirmSupervisorAgain(query));
      }

      // if (args?.rowData?.defectStatus && args?.rowData?.defectStatus === 11) {
      //   await equDefectConfirmMaintenance(query);
      // }
      if (
        args?.rowData?.defectStatus &&
        (args?.rowData?.defectStatus === 12 || args?.rowData?.defectStatus === 31)
      ) {
        await equDefectConfirmMeasure(query);
      }
      // if (args?.rowData?.defectStatus && args?.rowData?.defectStatus === 13) {
      //   await equDefectConfirmMember(query);
      // }

      // await (args?.type === 'edit' ? equInfoUpdate(query) : equInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDeviceDataSource([]);
      setEquipmentDataSource([]);
      form.resetFields();

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            equDefect.run(arg?.rowData?.id as unknown as string);
            // 回填数据
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDeviceDataSource([]);
    setEquipmentDataSource([]);
    form.resetFields();
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增缺陷流程',
          edit: '编辑缺陷流程',
          detail: '缺陷流程详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        labelWrap
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        {/* 缺陷上报 */}
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            width: '100%',
            padding: '20px 24px 10px'
          }}
        >
          <div style={{ fontSize: '16px' }}>设备详情</div>
          <Button
            type="primary"
            disabled={args?.type === 'detail'}
            onClick={() => {
              device.current?.open({
                onSuccess: (rows) => {
                  form?.setFieldsValue({
                    equipmentName: rows?.[0]?.equipmentName,
                    equipmentCode: rows?.[0]?.equipmentCode,
                    equipmentLocation: rows?.[0]?.storageLocation
                  });
                  setDeviceDataSource(rows || []);
                }
              });
            }}
          >
            设备关联
          </Button>
        </div>
        <Form.Item
          label="设备名称"
          name="equipmentName"
          rules={[
            {
              required: true,
              message: '请输入设备名称'
            }
          ]}
        >
          <Input placeholder="请输入设备名称" disabled />
        </Form.Item>
        <Form.Item
          label="设备编号"
          name="equipmentCode"
          rules={[
            {
              required: true,
              message: '请输入设备编号'
            }
          ]}
        >
          <Input placeholder="请输入设备编号" disabled />
        </Form.Item>
        <Form.Item
          label="设备位置"
          name="equipmentLocation"
          rules={[
            {
              required: false,
              message: '请输入设备位置'
            }
          ]}
        >
          <Input placeholder="请输入设备位置" disabled />
        </Form.Item>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            width: '100%',
            padding: '20px 24px 10px'
          }}
        >
          <div style={{ fontSize: '16px' }}>缺陷详情</div>
        </div>
        <Form.Item name="site" label="站点" rules={[{ required: true, message: '请选择站点' }]}>
          <Select
            disabled={
              !!(
                args?.rowData?.defectStatus &&
                args?.rowData?.defectStatus > 10 &&
                args?.rowData?.defectStatus !== 11 &&
                args?.rowData?.defectStatus !== 13 &&
                args?.rowData?.defectStatus !== 32 &&
                args?.rowData?.defectStatus !== 44
              ) || args?.type === 'detail'
            }
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择站点"
            options={(store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }))}
          />
        </Form.Item>
        <Form.Item
          label="缺陷等级"
          name="defectLevel"
          rules={[
            {
              required: true,
              message: '请选择缺陷等级'
            }
          ]}
        >
          <Select
            disabled={
              !!(
                args?.rowData?.defectStatus &&
                args?.rowData?.defectStatus > 10 &&
                args?.rowData?.defectStatus !== 11 &&
                args?.rowData?.defectStatus !== 13 &&
                args?.rowData?.defectStatus !== 32 &&
                args?.rowData?.defectStatus !== 44
              ) || args?.type === 'detail'
            }
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择缺陷等级"
            options={[
              {
                label: '一级',
                value: '一级'
              },
              {
                label: '二级',
                value: '二级'
              },
              {
                label: '三级高',
                value: '三级高'
              },
              {
                label: '三级中',
                value: '三级中'
              },
              {
                label: '三级低',
                value: '三级低'
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="缺陷类型"
          name="defectType"
          rules={[
            {
              required: true,
              message: '请选择缺陷类型'
            }
          ]}
        >
          <Select
            disabled={
              !!(
                args?.rowData?.defectStatus &&
                args?.rowData?.defectStatus > 10 &&
                args?.rowData?.defectStatus !== 11 &&
                args?.rowData?.defectStatus !== 13 &&
                args?.rowData?.defectStatus !== 32 &&
                args?.rowData?.defectStatus !== 44
              ) || args?.type === 'detail'
            }
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择缺陷类型"
            options={[
              {
                label: '设备缺陷',
                value: 1
              },
              {
                label: '生产缺陷',
                value: 2
              }
            ]}
          />
        </Form.Item>
        <Form.Item noStyle dependencies={['defectType']}>
          {({ getFieldValue }) => {
            const defectType = getFieldValue('defectType') || '';
            return defectType == 1 ? (
              <Form.Item
                label="故障类型"
                name="faultType"
                rules={[
                  {
                    required: true,
                    message: '请选择故障类型'
                  }
                ]}
              >
                <Select
                  disabled={
                    !!(
                      args?.rowData?.defectStatus &&
                      args?.rowData?.defectStatus > 10 &&
                      args?.rowData?.defectStatus !== 11 &&
                      args?.rowData?.defectStatus !== 13 &&
                      args?.rowData?.defectStatus !== 32 &&
                      args?.rowData?.defectStatus !== 44
                    ) || args?.type === 'detail'
                  }
                  style={{
                    width: '100%'
                  }}
                  allowClear
                  placeholder="请选择故障类型"
                  options={[
                    {
                      label: '设备',
                      value: '设备'
                    },
                    {
                      label: '电气',
                      value: '电气'
                    },
                    {
                      label: '仪控',
                      value: '仪控'
                    },
                    {
                      label: '土建',
                      value: '土建'
                    },
                    {
                      label: '车辆',
                      value: '车辆'
                    }
                  ]}
                />
              </Form.Item>
            ) : null;
          }}
        </Form.Item>

        <Form.Item
          label="缺陷描述"
          name="defectDescription"
          rules={[
            {
              required: true,
              message: '请输入缺陷描述'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入缺陷描述"
            disabled={
              !!(
                args?.rowData?.defectStatus &&
                args?.rowData?.defectStatus > 10 &&
                args?.rowData?.defectStatus !== 11 &&
                args?.rowData?.defectStatus !== 13 &&
                args?.rowData?.defectStatus !== 32 &&
                args?.rowData?.defectStatus !== 44
              ) || args?.type === 'detail'
            }
          />
        </Form.Item>
        <Form.Item
          label="上传附件"
          name="defectAttachment"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
            disabled={
              !!(
                args?.rowData?.defectStatus &&
                args?.rowData?.defectStatus > 10 &&
                args?.rowData?.defectStatus !== 11 &&
                args?.rowData?.defectStatus !== 13 &&
                args?.rowData?.defectStatus !== 32 &&
                args?.rowData?.defectStatus !== 44
              ) || args?.type === 'detail'
            }
            // base64
            //  accept="image/*"
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
        {/* end缺陷上报 */}
        {/* 设备工程师确认维修班组长 */}
        {args?.rowData?.defectStatus && args?.rowData?.defectStatus >= 10 && (
          <>
            <ProFormSelect
              disabled={
                !!(
                  args?.rowData?.defectStatus &&
                  args?.rowData?.defectStatus > 10 &&
                  args?.rowData?.defectStatus !== 11 &&
                  args?.rowData?.defectStatus !== 13 &&
                  args?.rowData?.defectStatus !== 32 &&
                  args?.rowData?.defectStatus !== 44
                ) || args?.type === 'detail'
              }
              name="processLeaderId"
              // label="维修班组长"
              dependencies={['defectType']}
              label={form?.getFieldValue('defectType') === 1 ? '维修班组长' : '生产班组长'}
              placeholder={
                form?.getFieldValue('defectType') === 1 ? '请选择维修班组长' : '请选择生产班组长'
              }
              rules={[
                {
                  required: true,
                  message:
                    form?.getFieldValue('defectType') === 1
                      ? '请选择维修班组长'
                      : '请选择生产班组长'
                }
              ]}
              request={async () => {
                const res = await orgUserInfoVoPage({
                  page: 1,
                  size: 1000,
                  roleName: form?.getFieldValue('defectType') === 1 ? '维修班组长' : '生产班组长'
                } as unknown as BASE.OrgUserInfochaxunduixiang);

                return (
                  res?.data?.records?.map((item) => {
                    return {
                      label: item?.fullName || item?.username,
                      value: item?.id
                    };
                  }) || []
                );
              }}
            />
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                width: '100%',
                padding: '20px 24px 10px'
              }}
            >
              <div style={{ fontSize: '16px' }}>备品备件详情</div>
              <Button
                type="primary"
                disabled={
                  args?.type === 'detail' ||
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  )
                }
                onClick={() => {
                  equipment.current?.open({
                    onSuccess: (rows) => {
                      const arr = rows?.filter(
                        (item) => !equipmentDataSource?.some((itm) => itm?.id === item?.id)
                      );
                      setEquipmentDataSource([...equipmentDataSource, ...arr]);
                    }
                  });
                }}
              >
                备件关联
              </Button>
            </div>
            {/* 表格 */}
            <Table<BizObject>
              size="small"
              columns={[
                {
                  title: '名称',
                  dataIndex: 'name',
                  align: 'center',
                  width: 100
                },
                {
                  title: '型号',
                  dataIndex: 'type',
                  align: 'center',
                  width: 100
                },
                {
                  title: '供应商',
                  dataIndex: 'supplier',
                  align: 'center',
                  width: 130
                },
                {
                  title: '数量',
                  dataIndex: 'number',
                  align: 'center',
                  width: 130
                },

                {
                  title: '操作',
                  fixed: 'right',
                  width: 150,
                  hidden:
                    args?.type === 'detail' ||
                    !!(
                      args?.rowData?.defectStatus &&
                      args?.rowData?.defectStatus > 10 &&
                      args?.rowData?.defectStatus !== 11 &&
                      args?.rowData?.defectStatus !== 13 &&
                      args?.rowData?.defectStatus !== 32 &&
                      args?.rowData?.defectStatus !== 44
                    ),
                  render: (text, record) => [
                    <a
                      key="delete"
                      onClick={() => {
                        if (args?.type === 'detail') return;
                        setEquipmentDataSource(
                          equipmentDataSource.filter((item) => item.id !== record.id)
                        );
                      }}
                    >
                      删除
                    </a>
                  ]
                }
              ]}
              dataSource={equipmentDataSource}
              scroll={{
                x: 'max-content'
              }}
              rowKey="id"
              bordered
              // {...table.tableProps}
              pagination={
                {
                  // ...table.tableProps.pagination,
                  // showTotal: (total) => `共 ${total} 条`,
                  // showQuickJumper: true,
                  // showSizeChanger: true,
                  // pageSizeOptions: ['10', '20', '50', '100']
                }
              }
            />
            {/* end表格 */}
            {/* <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                width: '100%',
                padding: '20px 24px 10px'
              }}
            ></div>
            <Form.Item
              label="危险点"
              name="dangerPoint"
              rules={[
                {
                  required: false,
                  message: '请选择危险点'
                }
              ]}
            >
              <Checkbox.Group
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
                options={[
                  {
                    label: '有毒液体',
                    value: '有毒液体'
                  },
                  {
                    label: '高空落物',
                    value: '高空落物'
                  },
                  {
                    label: '动火焊接',
                    value: '动火焊接'
                  },
                  {
                    label: '有限空间中毒窒息',
                    value: '有限空间中毒窒息'
                  },
                  {
                    label: '火灾',
                    value: '火灾'
                  },
                  {
                    label: '机械伤害',
                    value: '机械伤害'
                  },
                  {
                    label: '高处作业',
                    value: '高处作业'
                  },
                  {
                    label: '物体打击',
                    value: '物体打击'
                  },
                  {
                    label: '起重伤害',
                    value: '起重伤害'
                  },
                  {
                    label: '车辆伤害',
                    value: '车辆伤害'
                  },
                  {
                    label: '化学品泄露',
                    value: '化学品泄露'
                  },
                  {
                    label: '噪声',
                    value: '噪声'
                  },
                  {
                    label: '高温',
                    value: '高温'
                  },
                  {
                    label: '触电',
                    value: '触电'
                  },
                  {
                    label: '酸碱灼烫',
                    value: '酸碱灼烫'
                  }
                ]}
              />
            </Form.Item>
            <Form.Item
              label="预控措施"
              name="protectiveMeasure"
              rules={[
                {
                  required: false,
                  message: '请选择预控措施'
                }
              ]}
            >
              <Checkbox.Group
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
                options={[
                  {
                    label: '使用安全电压的手持电动工具',
                    value: '使用安全电压的手持电动工具'
                  },
                  {
                    label: '操作切换或阀门限位',
                    value: '操作切换或阀门限位'
                  },
                  {
                    label: '氧气瓶、乙炔瓶按规定存储,保持安全距离',
                    value: '氧气瓶、乙炔瓶按规定存储,保持安全距离'
                  },
                  {
                    label: '吹扫、清洗、置换易燃有毒液体',
                    value: '吹扫、清洗、置换易燃有毒液体'
                  },
                  {
                    label: '通信设备',
                    value: '通信设备'
                  },
                  {
                    label: '作业照明',
                    value: '作业照明'
                  },
                  {
                    label: '正确穿戴好个人防护用品,隔绝酸碱液体,防飞溅伤人',
                    value: '正确穿戴好个人防护用品,隔绝酸碱液体,防飞溅伤人'
                  },
                  {
                    label: '确认设备断电、停用后,再检维修;维修过程上锁挂牌',
                    value: '确认设备断电、停用后,再检维修;维修过程上锁挂牌'
                  },
                  {
                    label: '电工作业正确使用绝缘工具,穿绝缘鞋(绝缘靴),戴好绝缘手套',
                    value: '电工作业正确使用绝缘工具,穿绝缘鞋(绝缘靴),戴好绝缘手套'
                  },
                  {
                    label: '有限空间作业遵守先通风,再检测,后作业',
                    value: '有限空间作业遵守先通风,再检测,后作业'
                  },
                  {
                    label:
                      '吊装作业有司索工、信号工,遵守"十不吊"规定,吊物下及吊臂工作半径范围内不站人',
                    value:
                      '吊装作业有司索工、信号工,遵守"十不吊"规定,吊物下及吊臂工作半径范围内不站人'
                  }
                ]}
              />
            </Form.Item>
            <Form.Item
              label="其他危险点"
              name="dangerPointOther"
              rules={[
                {
                  required: false,
                  message: '请输入其他危险点'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入其他危险点"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <Form.Item
              label="其他预控措施"
              name="protectiveMeasureOther"
              rules={[
                {
                  required: false,
                  message: '请输入其他预控措施'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入其他预控措施"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                width: '100%',
                padding: '20px 24px 10px'
              }}
            >
              <div style={{ fontSize: '16px' }}>安全措施详情</div>
            </div>
            <Form.Item
              label="应隔离或停供的能源介质(如水、油、酸碱液体、气体)"
              name="measuresEnergy"
              rules={[
                {
                  required: false,
                  message: '请输入应隔离或停供的能源介质(如水、油、酸碱液体、气体)'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入应隔离或停供的能源介质(如水、油、酸碱液体、气体)"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <Form.Item
              label="保证工作安全、避免人身伤害的其他有效措施"
              name="measuresSafety"
              rules={[
                {
                  required: false,
                  message: '请输入保证工作安全、避免人身伤害的其他有效措施'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入保证工作安全、避免人身伤害的其他有效措施"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <Form.Item
              label="应设遮拦、应挂标示牌及其他防止误磋等措施"
              name="measuresWarning"
              rules={[
                {
                  required: false,
                  message: '请输入应设遮拦、应挂标示牌及其他防止误磋等措施'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入应设遮拦、应挂标示牌及其他防止误磋等措施"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <Form.Item
              label="其他需特别提醒的安全措施"
              name="measuresExtra"
              rules={[
                {
                  required: false,
                  message: '请输入其他需特别提醒的安全措施'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入其他需特别提醒的安全措施"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item>
            <Form.Item
              label="具体内容"
              name="measuresContent"
              rules={[
                {
                  required: false,
                  message: '请输入具体内容'
                }
              ]}
            >
              <Input.TextArea
                placeholder="请输入具体内容"
                disabled={
                  !!(
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus > 10 &&
                    args?.rowData?.defectStatus !== 11 &&
                    args?.rowData?.defectStatus !== 13 &&
                    args?.rowData?.defectStatus !== 32 &&
                    args?.rowData?.defectStatus !== 44
                  ) || args?.type === 'detail'
                }
              />
            </Form.Item> */}
          </>
        )}
        {/* end设备工程师确认维修班组长 */}
        {/* 设备工程师确认维修措施 */}
        {args?.rowData?.defectStatus &&
          args?.rowData?.defectStatus >= 11 &&
          args?.rowData?.defectStatus !== 32 &&
          args?.rowData?.defectStatus !== 44 && (
            <>
              <Form.Item
                label="是否能内修"
                name="maintenanceInternal"
                rules={[
                  {
                    required: true,
                    message: '请选择是否能内修'
                  }
                ]}
              >
                <Radio.Group
                  disabled={
                    !!(args?.rowData?.defectStatus && args?.rowData?.defectStatus > 11) ||
                    args?.type === 'detail'
                  }
                  options={[
                    { value: true, label: '是' },
                    { value: false, label: '否' }
                  ]}
                />
              </Form.Item>
              <Form.Item dependencies={[['maintenanceInternal']]} noStyle>
                {({ getFieldValue }) => {
                  const maintenanceInternal = getFieldValue(['maintenanceInternal']);

                  if (
                    maintenanceInternal === false &&
                    args?.rowData?.defectStatus &&
                    args?.rowData?.defectStatus >= 12
                  ) {
                    return (
                      <>
                        <Form.Item
                          label="维修措施"
                          name="maintenanceType"
                          rules={[
                            {
                              required: true,
                              message: '请选择维修措施'
                            }
                          ]}
                        >
                          <Radio.Group
                            disabled={
                              !!(
                                args?.rowData?.defectStatus &&
                                args?.rowData?.defectStatus > 12 &&
                                args?.rowData?.defectStatus !== 31
                              ) || args?.type === 'detail'
                            }
                            options={[
                              { value: '外修', label: '外修' },
                              { value: '挂起', label: '挂起' }
                            ]}
                          />
                        </Form.Item>
                        <Form.Item dependencies={[['maintenanceType']]} noStyle>
                          {({ getFieldValue }) => {
                            const maintenanceType = getFieldValue(['maintenanceType']);
                            if (maintenanceType === '外修') {
                              return (
                                <>
                                  <Form.Item
                                    label="维修单位"
                                    name="maintenanceUnit"
                                    rules={[
                                      {
                                        required: true,
                                        message: '请输入维修单位'
                                      }
                                    ]}
                                  >
                                    <Input
                                      placeholder="请输入维修单位"
                                      disabled={
                                        !!(
                                          args?.rowData?.defectStatus &&
                                          args?.rowData?.defectStatus > 12 &&
                                          args?.rowData?.defectStatus !== 31
                                        ) || args?.type === 'detail'
                                      }
                                    />
                                  </Form.Item>
                                  <Form.Item
                                    label="维修金额"
                                    name="maintenanceAmount"
                                    rules={[
                                      {
                                        required: false,
                                        message: '请输入维修金额'
                                      }
                                    ]}
                                  >
                                    <InputNumber
                                      placeholder="请输入维修金额"
                                      min={0}
                                      suffix="元"
                                      style={{ width: '100%' }}
                                      disabled={
                                        !!(
                                          args?.rowData?.defectStatus &&
                                          args?.rowData?.defectStatus > 12 &&
                                          args?.rowData?.defectStatus !== 31
                                        ) || args?.type === 'detail'
                                      }
                                    />
                                  </Form.Item>
                                  <Form.Item
                                    label="维修附件"
                                    name="maintenanceAttachment"
                                    rules={[
                                      {
                                        required: false,
                                        message: '请上传附件'
                                      }
                                    ]}
                                  >
                                    <Upload
                                      disabled={
                                        !!(
                                          args?.rowData?.defectStatus &&
                                          args?.rowData?.defectStatus > 12 &&
                                          args?.rowData?.defectStatus !== 31
                                        ) || args?.type === 'detail'
                                      }
                                      // base64
                                      //  accept="image/*"
                                    >
                                      <Button>上传</Button>
                                    </Upload>
                                  </Form.Item>
                                  <Form.Item
                                    label="是否厂内维修"
                                    name="maintenanceInHouse"
                                    rules={[
                                      {
                                        required: true,
                                        message: '请选择是否厂内维修'
                                      }
                                    ]}
                                  >
                                    <Radio.Group
                                      disabled={
                                        !!(
                                          args?.rowData?.defectStatus &&
                                          args?.rowData?.defectStatus > 12 &&
                                          args?.rowData?.defectStatus !== 31
                                        ) || args?.type === 'detail'
                                      }
                                      options={[
                                        { value: true, label: '是' },
                                        { value: false, label: '否' }
                                      ]}
                                    />
                                  </Form.Item>

                                  {/* <Form.Item
                                    label="备注"
                                    name="maintenanceRemark"
                                    rules={[
                                      {
                                        required: true,
                                        message: '请输入备注'
                                      }
                                    ]}
                                  >
                                    <Input.TextArea
                                      placeholder="请输入备注"
                                      autoSize={{ minRows: 2, maxRows: 4 }}
                                      disabled={
                                        !!(
                                          args?.rowData?.defectStatus &&
                                          args?.rowData?.defectStatus > 12 &&
                                          args?.rowData?.defectStatus !== 31
                                        ) || args?.type === 'detail'
                                      }
                                    />
                                  </Form.Item> */}
                                </>
                              );
                            }
                            return null;
                          }}
                        </Form.Item>
                      </>
                    );
                  }

                  return null;
                }}
              </Form.Item>
              {(maintenanceInternal || maintenanceInHouse) &&
                (args?.rowData?.defectStatus === 11 ||
                  (args?.rowData?.defectStatus >= 13 && args?.rowData?.defectStatus !== 31)) && (
                  <>
                    <ProFormSelect
                      name="maintenanceLeaderId"
                      dependencies={['defectType']}
                      showSearch={true}
                      label={form?.getFieldValue('defectType') === 1 ? '维修组长' : '运行人员'}
                      placeholder={`请选择${form?.getFieldValue('defectType') === 1 ? '维修组长' : '运行人员'}`}
                      rules={[
                        {
                          required: true,
                          message: `请选择${form?.getFieldValue('defectType') === 1 ? '维修组长' : '运行人员'}`
                        }
                      ]}
                      request={async () => {
                        const res = await orgUserInfoVoPage({
                          page: 1,
                          size: 1000,
                          roleName:
                            form?.getFieldValue('defectType') === 1 ? '维修组长' : '运行人员'
                        } as unknown as BASE.OrgUserInfochaxunduixiang);

                        return (
                          res?.data?.records?.map((item) => {
                            return {
                              label: item?.fullName || item?.username,
                              value: item?.id
                            };
                          }) || []
                        );
                      }}
                    />
                    {/* <Form.Item
                      label="维修成员"
                      name="maintenanceMember"
                      rules={[{ required: true, message: '请输入维修成员' }]}
                    >
                      <Input.TextArea placeholder="请输入维修成员" />
                    </Form.Item> */}
                    <div style={{ position: 'relative' }}>
                      <ProFormSelect
                        name="maintenanceMember"
                        showSearch={true}
                        style={{ width: '90%' }}
                        mode="multiple"
                        label="维修成员"
                        placeholder="请选择维修成员"
                        rules={[
                          {
                            required: true,
                            message: `请选择维修成员`
                          }
                        ]}
                        request={async () => {
                          const res = await safeEmployeeCertificatesUserList();

                          return (
                            res?.data?.map((item) => {
                              return {
                                label: item,
                                value: item
                              };
                            }) || []
                          );
                        }}
                      />
                      <div
                        style={{
                          color: '#005bac',
                          cursor: 'pointer',
                          position: 'absolute',
                          right: '17%',
                          top: '2px',
                          zIndex: 1
                        }}
                      >
                        <Tooltip title="查看维修成员持证情况">
                          <Icon
                            icon="ri:id-card-line"
                            onClick={() => {
                              const people = form.getFieldValue('maintenanceMember');

                              if (people.length > 0) {
                                paper.current?.open({
                                  userList: people
                                });
                              }
                            }}
                            fontSize={30}
                          />
                        </Tooltip>
                      </div>
                    </div>
                    {/* 
                    <Form.Item
                      noStyle
                      shouldUpdate={(prevValues, currentValues) =>
                        prevValues.maintenanceMember !== currentValues.maintenanceMember
                      }
                    >
                      {({ getFieldValue }) =>
                        getFieldValue('maintenanceMember')?.length > 0 ? ( */}
                    <Form.Item
                      label="维修成员共计"
                      name="maintenanceMemberTotal"
                      rules={[{ required: true, message: '请输入维修成员共计人数' }]}
                    >
                      <InputNumber
                        placeholder="请输入维修成员共计人数"
                        style={{ width: '100%' }}
                        step={1}
                        min={0}
                        addonAfter="人"
                      />
                    </Form.Item>
                    {/* ) : null
                      }
                    </Form.Item> */}

                    {/* <Form.Item
                      label="共计"
                      name="maintenanceMemberTotal"
                      dependencies={['maintenanceMember']}
                      rules={[{ required: true, message: '请输入共计' }]}
                    >
                      <InputNumber
                        placeholder="请输入共计"
                        style={{ width: '100%' }}
                        step={1}
                        min={0}
                        addonAfter="人"
                      />
                    </Form.Item> */}
                    <Form.Item
                      label="计划时间"
                      name="maintenancePlan"
                      rules={[{ required: true, message: '请选择计划时间' }]}
                    >
                      <DatePicker.RangePicker format="YYYY-MM-DD" />
                    </Form.Item>
                    <Form.Item
                      label="是否需要开工作票"
                      name="ticketBinding"
                      rules={[{ required: true, message: '请选择是否需要开工作票' }]}
                    >
                      <Radio.Group
                        options={[
                          { value: true, label: '是' },
                          { value: false, label: '否' }
                        ]}
                      />
                    </Form.Item>

                    <Form.Item dependencies={[['ticketBinding']]} noStyle>
                      {({ getFieldValue }) => {
                        const ticketBinding = getFieldValue(['ticketBinding']);
                        return ticketBinding ? (
                          <Form.Item
                            label="工作票类型"
                            name={['ticketType']}
                            rules={[{ required: true, message: '请选择工作票类型' }]}
                          >
                            <Select
                              placeholder="请选择工作票类型"
                              options={[
                                { value: '气浮减速机类', label: '气浮减速机类' },
                                { value: '泵类', label: '泵类' },
                                { value: '阀门类', label: '阀门类' },
                                { value: '芬顿曝气头类', label: '芬顿曝气头类' },
                                { value: '管道类', label: '管道类' },
                                { value: '模组异位清洗类', label: '模组异位清洗类' }
                              ]}
                            />
                          </Form.Item>
                        ) : null;
                      }}
                    </Form.Item>
                  </>
                )}
            </>
          )}
        {/* end设备工程师确认维修措施 */}
      </Form>
      <Device ref={device} />
      <Equipment ref={equipment} />
      <Paper ref={paper} />
    </Drawer>
  );
};

export default forwardRef(Edit);
